package org.teamh.connection.json.handler;

import org.teamh.connection.json.event.JsonEventObject;
import org.teamh.game.Start;
import org.teamh.logic.datamodel.*;

public class MapHandler extends JsonMasterHandler {

	public MapHandler(Start start, DatamodelManager manager) {
		super(start, manager);
	}
	
	public boolean handleMsg(JsonEventObject json) {
		
		if (json.getSource().startsWith("Map")) {
			if (json.getProperty().equals("background")) {
				manager.getMap(json.getSource()).setBackground(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("cells")) {
				Cell cell = manager.getCell(json.getNewValue());
				if(cell == null) {
					cell = new Cell(json.getNewValue());
					manager.addCell(cell);
				}
				manager.getMap(json.getSource()).addCell(cell);
				return true;
			} else if (json.getProperty().equals("name")) {
				manager.getMap(json.getSource()).setName(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("tile")) {
				manager.getMap(json.getSource()).setTile(manager.getTile(json.getNewValue()));
				return true;
			} else if (json.getProperty().equals("enterWaypoint")) {
				Waypoint enterWaypoint = manager.getWaypoint(json.getNewValue());
				if(enterWaypoint == null) {
					enterWaypoint = new Waypoint(json.getNewValue());
					manager.getMap(json.getSource()).setEnterWaypoint(enterWaypoint);
				}
				manager.addWaypoint(enterWaypoint);
				manager.getMap(json.getSource()).getWaypoint(json.getNewValue()).setIndex(0);
				start.getModel().setCount(0);
				return true;
			} else if (json.getProperty().equals("exitWaypoint")) {
				manager.getMap(json.getSource()).setExitWaypoint(manager.getWaypoint(json.getNewValue()));
				start.getModel().setCount(start.getModel().getCount() + 1);
				manager.getWaypoint(json.getNewValue()).setIndex(start.getModel().getCount());
				return true;
			} else if (json.getProperty().equals("waypoints")) {
				manager.getMap(json.getSource()).addWaypoint(manager.getWaypoint(json.getNewValue()));
				return true;
			} else if (json.getProperty().equals("createdBy")) {
				manager.getMap(json.getSource()).setCreatedBy(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("version")) {
				manager.getMap(json.getSource()).setVersion(Integer.parseInt(json.getNewValue()));
				return true;
			}
			return false;
		} else {
			return false;
		}	
	}
}